package com.hqq.exercise.tree;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * LevelTraversalTree 层序遍历二叉树
 * 题目描述:
 * 从上往下打印二叉树的每个结点，同一层的结点按照从左到右的顺序打印。
 * Created by heqianqian on 2017/8/13.
 */
public class LevelTraversalTree {

    public static void printByLoop(TreeNode root) {
        Queue<TreeNode> queue = new LinkedBlockingQueue<>();
        if (root == null) {//如果二叉树为空
            return;
        }
        while (root != null) {
            System.out.print(root.val + " ");
            if (root.left != null) {
                queue.add(root.left);
            }
            if (root.right != null) {
                queue.add(root.right);
            }
            root = queue.poll();
        }
    }

    public static void printByRecursion(TreeNode root) {
        if (root == null) {
            return;
        }
        int dep = depth(root);

        for (int i = 1; i <=dep; i++) {
            print(root, i);
        }
    }

    private static void print(TreeNode root, int level) {
        if (root == null || level < 1) {
            return;
        }
        if (level == 1) {
            System.out.print(root.val + " ");
        }
        print(root.left, level - 1);
        print(root.right, level - 1);
    }

    private static int depth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        //计算左右子树的高度
        int left = depth(root.left);
        int right = depth(root.right);

        if (left > right) {
            return left + 1;
        } else {
            return right + 1;
        }
    }
}

